package com.cskaoyan.batch;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

// 批处理的demo
public class BatchDemo {

    public static void main(String[] args) throws SQLException {

//        long startTime = System.currentTimeMillis();
//        normalbatch();
//        long t1 = System.currentTimeMillis();
//        statementBatch();
        long t2 = System.currentTimeMillis();
        prepareStatement();
        long endTime = System.currentTimeMillis();


//        System.out.println("normal-batch:" + (t1- startTime)+ " 毫秒" );
//        System.out.println("statement-batch:" + (t2- t1)+ " 毫秒" );
        System.out.println("prepareStatement-batch:" + (endTime- t2+ " 毫秒" ));

    }



    // normal
    public static void normalbatch() throws SQLException {

        Connection connection = JDBCUtils.getConnection();

        Statement statement = connection.createStatement();

        for (int i = 0; i < 1000; i++) {
            int affectedRows = statement.executeUpdate("insert into user values (null,'zhangfei','dage','俺也一样')");
            System.out.println("affectedRows:" + affectedRows);
        }
        JDBCUtils.closeResources(connection,statement,null);

    }

    // statement
    public static void statementBatch() throws SQLException {

        Connection connection = JDBCUtils.getConnection();

        Statement statement = connection.createStatement();

        // 添加SQL语句到batch里面
        for (int i = 0; i < 1000; i++) {
            statement.addBatch("insert into user values (null,'liubei','kuangfuhanshi','我二弟天下无敌')");
        }
        // 这个数组里面是每个SQL语句影响的行数
        int[] arr = statement.executeBatch();

        JDBCUtils.closeResources(connection,statement,null);

    }

    // prepareStatement
    public static void prepareStatement() throws SQLException {


        Connection connection = JDBCUtils.getConnection();

        PreparedStatement preparedStatement = connection.prepareStatement("insert into user values (null,?,?,?)");

        for (int i = 0; i < 10000000; i++) {

            preparedStatement.setString(1,"曹操");
            preparedStatement.setString(2,"我头不痛");
            preparedStatement.setString(3,"宁教我负天下人");

            preparedStatement.addBatch();
        }
        // 这个arr数组里面不是影响的行数，而是SQL语句是否成功 （-2，-2，-2） Statement.SUCCESS_NO_INFO  = -2
        int[] arr = preparedStatement.executeBatch();

        JDBCUtils.closeResources(connection,preparedStatement,null);

    }


}
